import os
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import logging
import re
import urllib
from gdb import Log

from base import BaseHandler

import constants

Said_Words=re.compile("/say/(?P<words>)")

class SayListHandler(BaseHandler):
   def say(self):
       self.template_values[constants.Verb_Desc]=constants.verb2desc["say"]
       self.send_to_template("home.html",self.template_values)
   def user_do(self,name,email):
       self.say()
      
   def non_user_do(self):
       self.say()

class SaidHandler(BaseHandler):
   def said(self):
       # extract what logger said
       result = re.search(r"said/(?P<words>.*)", self.request.url)
       words=format_words(result.group("words"))
       
       # compile these words into the logging url
       if constants.User_Name in self.template_values:
            name=self.template_values[constants.User_Name]
       if ((name == None) | (name == "")):
           name="test"
       url = constants.Domain_URL + "/" + name +  "/said/" + words
       logging.info("Log New url : " + url)
       
       u = Log(url=url,user=name)
       u.put()
       # logging.info("Save New url : " + u)
       
       # print out
       self.template_values[constants.Verb_Desc]=constants.verb2desc["say"]
       self.template_values[constants.Last_Logged]=url
       self.list_all_log(name,self.template_values)
         
       self.send_to_template("home.html",self.template_values)
   
   def user_do(self,name,email):
       self.said()
      
   def non_user_do(self):
       self.say()
              
# the logger is saying sth
class SayingHandler(BaseHandler):
   def said(self):
      result = re.search(r"say/(?P<words>.*)", self.request.url)
      words = format_words(result.group("words"))
      logging.info("Saying : " + words)
      
      self.template_values[constants.Saying_Words] = words
      self.template_values[constants.Update_Verb] = "said"
      self.template_values[constants.Verb_Desc]=constants.verb2desc["say"]
      
      self.send_to_template("home.html",self.template_values)
   
   def user_do(self,name,email):
       self.said()
      
   def non_user_do(self):
       self.said()

def is_quoted(s):
    return True
def format_words(words):
    if(is_quoted):
        return urllib.unquote(words)
    return words

application = webapp.WSGIApplication([('/say', SayListHandler),('/say/.*', SayingHandler),
                                      ('/said/.*', SaidHandler)],debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
    main()